<template>
  <div class="sales">
    <div class="pos-interface">
      <!-- 左侧操作区 -->
      <div class="pos-left">
        <div class="pos-search">
          <input 
            v-model="searchQuery"
            type="text" 
            placeholder="扫码或输入药品名称..." 
            @keyup.enter="addToCart"
          >
          <button @click="addToCart">添加</button>
        </div>
        
        <div class="cart-container">
          <h4>购物车</h4>
          <div class="cart-items">
            <div v-if="cartItems.length === 0" class="empty-cart">
              购物车为空
            </div>
            <div 
              v-for="item in cartItems" 
              :key="item.id"
              class="cart-item"
            >
              <div class="item-info">
                <strong>{{ item.name }}</strong>
                <div 
                  v-if="item.isPrescription"
                  class="prescription-warning"
                >
                  🔴 处方药
                </div>
              </div>
              <div class="item-price">
                <div class="quantity-controls">
                  <button @click="updateQuantity(item.id, -1)">-</button>
                  <span>{{ item.quantity }}</span>
                  <button @click="updateQuantity(item.id, 1)">+</button>
                </div>
                <div>{{ item.quantity }}盒 × ¥{{ item.price.toFixed(2) }}</div>
                <div><strong>¥{{ (item.quantity * item.price).toFixed(2) }}</strong></div>
              </div>
              <button 
                class="remove-btn"
                @click="removeFromCart(item.id)"
              >
                ×
              </button>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 右侧结算区 -->
      <div class="pos-right">
        <div class="total-display">
          总计: ¥{{ totalAmount.toFixed(2) }}
        </div>
        
        <div 
          v-if="hasPrescriptionDrugs"
          class="prescription-alert"
        >
          ⚠️ 购物车包含处方药，需要提供处方
        </div>
        
        <div class="payment-section">
          <h5>支付方式</h5>
          <div class="payment-buttons">
            <button 
              v-for="method in paymentMethods"
              :key="method.key"
              class="payment-btn"
              :class="{ active: selectedPayment === method.key }"
              @click="selectPayment(method.key)"
            >
              {{ method.icon }} {{ method.label }}
            </button>
          </div>
        </div>
        
        <button 
          class="checkout-btn"
          :disabled="cartItems.length === 0"
          @click="checkout"
        >
          结算
        </button>
      </div>
    </div>

    <!-- 销售记录 -->
    <div class="sales-records">
      <h4 class="section-title">今日销售记录</h4>
      <table class="data-table">
        <thead>
          <tr>
            <th>时间</th>
            <th>药品名称</th>
            <th>数量</th>
            <th>金额</th>
            <th>支付方式</th>
            <th>操作员</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="record in salesRecords" :key="record.id">
            <td>{{ record.time }}</td>
            <td>{{ record.drugName }}</td>
            <td>{{ record.quantity }}</td>
            <td>¥{{ record.amount.toFixed(2) }}</td>
            <td>{{ record.paymentMethod }}</td>
            <td>{{ record.operator }}</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'

interface CartItem {
  id: string
  name: string
  price: number
  quantity: number
  isPrescription: boolean
}

interface SalesRecord {
  id: string
  time: string
  drugName: string
  quantity: number
  amount: number
  paymentMethod: string
  operator: string
}

interface PaymentMethod {
  key: string
  label: string
  icon: string
}

// 响应式数据
const searchQuery = ref('')
const selectedPayment = ref('cash')
const cartItems = ref<CartItem[]>([
  {
    id: 'C001',
    name: '阿莫西林胶囊',
    price: 18.50,
    quantity: 2,
    isPrescription: true
  },
  {
    id: 'C002',
    name: '感冒灵颗粒',
    price: 12.80,
    quantity: 1,
    isPrescription: false
  }
])

const paymentMethods: PaymentMethod[] = [
  { key: 'cash', label: '现金', icon: '💵' },
  { key: 'wechat', label: '微信支付', icon: '💚' },
  { key: 'alipay', label: '支付宝', icon: '🔵' },
  { key: 'card', label: '银行卡', icon: '💳' }
]

const salesRecords = ref<SalesRecord[]>([
  {
    id: 'S001',
    time: '14:25',
    drugName: '布洛芬片',
    quantity: 2,
    amount: 31.20,
    paymentMethod: '微信支付',
    operator: '张医生'
  },
  {
    id: 'S002',
    time: '14:18',
    drugName: '复方甘草片',
    quantity: 1,
    amount: 8.50,
    paymentMethod: '现金',
    operator: '李护士'
  },
  {
    id: 'S003',
    time: '14:10',
    drugName: '阿莫西林胶囊',
    quantity: 3,
    amount: 55.50,
    paymentMethod: '支付宝',
    operator: '张医生'
  }
])

// 计算属性
const totalAmount = computed(() => {
  return cartItems.value.reduce((total, item) => {
    return total + item.price * item.quantity
  }, 0)
})

const hasPrescriptionDrugs = computed(() => {
  return cartItems.value.some(item => item.isPrescription)
})

// 方法
const addToCart = () => {
  if (!searchQuery.value.trim()) return
  
  // 模拟添加商品
  const newItem: CartItem = {
    id: `C${Date.now()}`,
    name: searchQuery.value,
    price: Math.random() * 50 + 10, // 随机价格
    quantity: 1,
    isPrescription: Math.random() > 0.7 // 30% 概率是处方药
  }
  
  cartItems.value.push(newItem)
  searchQuery.value = ''
}

const updateQuantity = (itemId: string, change: number) => {
  const item = cartItems.value.find(item => item.id === itemId)
  if (item) {
    item.quantity = Math.max(1, item.quantity + change)
  }
}

const removeFromCart = (itemId: string) => {
  const index = cartItems.value.findIndex(item => item.id === itemId)
  if (index !== -1) {
    cartItems.value.splice(index, 1)
  }
}

const selectPayment = (method: string) => {
  selectedPayment.value = method
}

const checkout = () => {
  if (cartItems.value.length === 0) return
  
  if (hasPrescriptionDrugs.value) {
    if (!confirm('购物车包含处方药，请确认已查验处方，是否继续结算？')) {
      return
    }
  }
  
  // 创建销售记录
  const now = new Date()
  const newRecord: SalesRecord = {
    id: `S${Date.now()}`,
    time: now.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }),
    drugName: cartItems.value.map(item => item.name).join(', '),
    quantity: cartItems.value.reduce((total, item) => total + item.quantity, 0),
    amount: totalAmount.value,
    paymentMethod: paymentMethods.find(m => m.key === selectedPayment.value)?.label || '现金',
    operator: '张医生'
  }
  
  salesRecords.value.unshift(newRecord)
  cartItems.value = []
  
  alert(`结算完成！金额: ¥${newRecord.amount.toFixed(2)}`)
}
</script>

<style scoped>
.sales {
  font-size: 12px;
}

.pos-interface {
  display: grid;
  grid-template-columns: 1fr 250px;
  gap: 20px;
  margin-bottom: 30px;
  height: 400px;
}

.pos-left {
  display: flex;
  flex-direction: column;
  background: white;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 15px;
}

.pos-search {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.pos-search input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 12px;
}

.pos-search button {
  background: #3498db;
  color: white;
  border: none;
  padding: 8px 15px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.pos-search button:hover {
  background: #2980b9;
}

.cart-container {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.cart-container h4 {
  margin-bottom: 10px;
  color: #333;
  font-size: 13px;
}

.cart-items {
  flex: 1;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 10px;
  background: #f9f9f9;
  overflow-y: auto;
}

.empty-cart {
  text-align: center;
  color: #999;
  padding: 20px;
}

.cart-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #eee;
  position: relative;
}

.cart-item:last-child {
  border-bottom: none;
}

.item-info strong {
  display: block;
  margin-bottom: 2px;
}

.prescription-warning {
  font-size: 10px;
  color: #e74c3c;
  font-weight: bold;
}

.item-price {
  text-align: right;
  font-size: 11px;
}

.quantity-controls {
  display: flex;
  align-items: center;
  gap: 5px;
  margin-bottom: 2px;
}

.quantity-controls button {
  background: #ddd;
  border: none;
  width: 20px;
  height: 20px;
  border-radius: 2px;
  cursor: pointer;
  font-size: 12px;
}

.quantity-controls button:hover {
  background: #ccc;
}

.remove-btn {
  position: absolute;
  top: 5px;
  right: 5px;
  background: #e74c3c;
  color: white;
  border: none;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  cursor: pointer;
  font-size: 10px;
  line-height: 1;
}

.pos-right {
  background: #f8f9fa;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 15px;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.total-display {
  background: #4CAF50;
  color: white;
  padding: 15px;
  border-radius: 4px;
  text-align: center;
  font-size: 16px;
  font-weight: bold;
}

.prescription-alert {
  background: #fff3cd;
  color: #856404;
  padding: 8px 10px;
  border-radius: 4px;
  font-size: 11px;
  border: 1px solid #ffeaa7;
}

.payment-section h5 {
  margin-bottom: 8px;
  color: #333;
  font-size: 12px;
}

.payment-buttons {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.payment-btn {
  background: white;
  border: 1px solid #ddd;
  padding: 8px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 11px;
  text-align: left;
  transition: all 0.2s;
}

.payment-btn:hover {
  background: #e8f4f8;
}

.payment-btn.active {
  background: #3498db;
  color: white;
  border-color: #3498db;
}

.checkout-btn {
  background: #27ae60;
  color: white;
  border: none;
  padding: 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
  font-weight: bold;
}

.checkout-btn:hover:not(:disabled) {
  background: #219a52;
}

.checkout-btn:disabled {
  background: #95a5a6;
  cursor: not-allowed;
}

.section-title {
  margin: 20px 0 10px 0;
  font-size: 13px;
  color: #333;
  font-weight: bold;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #ddd;
  font-size: 12px;
}

.data-table th {
  background: #f8f9fa;
  border: 1px solid #ddd;
  padding: 6px 8px;
  text-align: left;
  font-weight: bold;
  font-size: 11px;
  color: #666;
}

.data-table td {
  border: 1px solid #ddd;
  padding: 4px 8px;
}

.data-table tr:nth-child(even) {
  background: #f9f9f9;
}

.data-table tr:hover {
  background: #e8f4f8;
}

/* 响应式 */
@media (max-width: 768px) {
  .pos-interface {
    grid-template-columns: 1fr;
    height: auto;
  }
  
  .pos-right {
    order: -1;
  }
}
</style> 